<?php

require_once("../db/db.php");
require_once("../tags/tags.php");

define("PACKAGES_FOLDER", "../../packages_data");
define("RELATIVE_CONTENT_FOLDER", "../../content_data");
define("REAL_CONTENT_FOLDER", "content_data");
	
class Content {
		
	public function __construct() {
	}
	
	public function addContent($packageName, $fileName, $tags, $corpus) {
		$db = new Database();
		
		$hashName = hash_file('md5', PACKAGES_FOLDER . '/' . $packageName . '/' . $fileName);
		$ext = pathinfo($fileName, PATHINFO_EXTENSION);
		$path = RELATIVE_CONTENT_FOLDER . '/' . $hashName . '.' . $ext;
		$db_path = REAL_CONTENT_FOLDER . '/' . $hashName . '.' . $ext; 
		
      	if (copy(PACKAGES_FOLDER . '/' . $packageName . '/' . $fileName, $path)) {
			
			$contentId = $db->getMax("content", "id", true);
			$db->executeQuery("INSERT INTO content(id, path,ime,id_zbirke) VALUES ('" . $contentId . "', '" . $db_path . "', '" . $fileName . "', '" . $corpus . "');");
			
			unlink(PACKAGES_FOLDER . '/' . $packageName . '/' . $fileName);
			
			foreach($tags as $tag) {
				$parts = explode("=",$tag);
				
				$tagResult = false;
				if (count($parts) == 2) {
					$tagResult = $db->executeQuery("SELECT id FROM tag WHERE name='" . $parts[0] . "' AND parameter='" . $parts[1] . "';");
				}
				else {
					$tagResult = $db->executeQuery("SELECT id FROM tag WHERE name='" . $tag . "';");
				}
				
				if ($tagResult) {
					$tagResult = $db->parseIntegers($tagResult, "id");
					$tagId = $tagResult[0]["id"];
					$tagContentId = $db->getMax("tag_content", "id", true);
					$db->executeQuery("INSERT INTO tag_content(id, tag_id, content_id) VALUES (" . $tagContentId . ", " . $tagId . ", " . $contentId . ");");
				}
			}
      	}
		else {
			return false;
		}
		
		return true;
	}
	
	public function getContent($tagIds) {
		$db = new Database();
		
		$contentIds = array();
		foreach ($tagIds as $tagId) {
			// Select all content ids from content
			$query = "SELECT content_id FROM tag_content WHERE tag_id=" . $tagId;

			$data = $db->executeQuery($query);
			
			if ($data && count($data) > 0) {
				$tagResult = $db->parseIntegers($data, "content_id");
				foreach ($tagResult as $row) {
					$contentIds[] = $row["content_id"];
				}
			}
		}
		
		$return = array();
		foreach($contentIds as $contentId) {
			$result = $db->executeQuery("SELECT * FROM content WHERE id=" . $contentId);
			if ($result && count($result) > 0) {
				$result = $db->parseIntegers($result, "id");
				$result = $db->parseIntegers($result, "id_zbirke");
				$return[] = $result[0];
			}
		}
		
		return $return;
	}

	public function __destruct() {
	}
}
?>
